let xhr;
const baseURL = "";
let params = {};
$(document).ready(function () {
  const tomorrow = new Date(new Date().getTime() + 1000 * 3600 * 24);
  $("#expiryTime").val(dateFormat("YYYY-mm-dd", tomorrow));
  $("#expiryTime")[0].setAttribute("min", dateFormat("YYYY-mm-dd", tomorrow));
  $("#code").bind("input", debounce(onInput, 1000));
  $(".submit-btn").bind("click", generate);
  $('.btn-secondary').bind("click", reset);
});

function onInput() {
  const code = $(this).val();
  if (code) {
    getParams(code);
  }
}

function reset() {
  $(".iplist").html("");
  $(".maclist").html("");
  $(".detail").html("");
}

function getParams(code) {
  if (xhr) {
    xhr.abort();
    xhr = null;
  }

  $(".loading").show();
  xhr = $.ajax({
    url: baseURL + "/decode",
    method: "post",
    dataType: "json",
    data: { code },
    success(res) {
      if (res.code !== 200) {
        alert("申请码错误");
        return;
      }

      const data = res.data;
      params = res.data.params;

      // 重置checkbox
      $("#ipCheck").prop("checked", false)
      $("#macCheck").prop("checked", false)
      $("#boardCheck").prop("checked", false)
      $("#cpuCheck").prop("checked", false)


      let html = "";
      Object.entries(params).forEach(([key, type]) => {
        let inputType = {
          "java.util.Date": "date",
          "java.lang.String": "text",
          "java.lang.Integer": "number",
          "java.lang.Long": "number",
        }[type];

        if (!inputType) inputType = "text";

        html += `
          <div class="mb-3 row">
            <label for="${key}" class="col-2 form-label">
              <span class="required">*</span>
            ${key}:</label>
            <div class="col-10">
              <input class="form-control" type="${inputType}" name="${key}" id="${key}" required ${
          inputType === "number" ? "min='0'" : ""
        }/>
                <div class="invalid-feedback">
                    请输入${key}
                </div>
            </div>
          </div>
        `;
      });
      $(".detail").html(html);

      let ipListHtml = "";
      data.ipAddress.map((ip) => {
        ipListHtml += `
          <div>${ip}</div>
        `;
      });
      $(".iplist").html(ipListHtml);

      let macListHtml = "";
      data.macAddress.map((mac) => {
        macListHtml += `
          <div>${mac}</div>
        `;
      });
      $(".maclist").html(macListHtml);

      $("#mainBoardSerial").val(data.mainBoardSerial);
      $("#cpuSerial").val(data.cpuSerial);
    },
    complete() {
      $(".loading").hide();
    },
  });
}

function generate(e) {
  e.preventDefault();

  const code = $("#code").val();
  const expiryTime = $("#expiryTime").val();
  const paramList = Object.keys(params).reduce((res, key) => {
    res[key] = $("#" + key).val() || "";
    return res;
  }, {});

  const ipCheck = Boolean($("#ipCheck").prop("checked")),
      macCheck = Boolean($("#macCheck").prop("checked")),
      boardCheck = Boolean($("#boardCheck").prop("checked")),
      cpuCheck = Boolean($("#cpuCheck").prop("checked")),
      mainBoardSerial = $("#mainBoardSerial").val(),
      cpuSerial = $("#cpuSerial").val();

  if (boardCheck) {
    $("#mainBoardSerial").attr("required", "true");
  }
  if (cpuCheck) {
    $("cpuSerial").attr("required", "true");
  }

  let valid = $("form")[0].checkValidity();
  $("form")[0].classList.add("was-validated");
  if (!valid) return;

  // 模拟表单提交同步方式下载文件
  // 能够弹出保存文件对话框
  const url = baseURL + "/generate";
  let form = $("<form></form>").attr("action", url).attr("method", "post");
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "expiryTime")
          .attr("value", expiryTime)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "code")
          .attr("value", code)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "ipCheck")
          .attr("value", ipCheck)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "macCheck")
          .attr("value", macCheck)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "boardCheck")
          .attr("value", boardCheck)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "cpuCheck")
          .attr("value", cpuCheck)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "mainBoardSerial")
          .attr("value", mainBoardSerial)
  );
  form.append(
      $("<input></input>")
          .attr("type", "hidden")
          .attr("name", "cpuSerial")
          .attr("value", cpuSerial)
  );
  Object.keys(params).forEach((param) => {
    form.append(
        $("<input></input>")
            .attr("type", "hidden")
            .attr("name", `params.${param}`)
            .attr("value", paramList[param])
    );
  });

  form.appendTo("body").submit().remove();

  $("#mainBoardSerial").removeAttr("required");
  $("cpuSerial").removeAttr("required");
}
